package com.loopj.ohos.http.sample;

import com.loopj.ohos.http.AsyncHttpClient;
import com.loopj.ohos.http.AsyncHttpRequest;
import com.loopj.ohos.http.AsyncHttpResponseHandler;
import com.loopj.ohos.http.ResponseHandlerInterface;
import com.loopj.ohos.http.ext.LocalHiLog;
import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.client.methods.HttpUriRequest;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
import cz.msebera.android.httpclient.protocol.HttpContext;
import ohos.aafwk.ability.delegation.AbilityDelegatorRegistry;
import ohos.app.Context;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.assertNull;

public class ExampleTest {
    @Test
    public void onStart() {
    }



    @Test
    public void testGet() {
        final Boolean[] resultFlg = {false};
        final CountDownLatch signal = new CountDownLatch(1);

        AsyncHttpClient asyncHttpClient = new AsyncHttpClient() {
            @Override
            protected AsyncHttpRequest newAsyncHttpRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) {
                return super.newAsyncHttpRequest(client, httpContext, uriRequest, contentType, responseHandler, context);
            }
        };

        asyncHttpClient.get(AbilityDelegatorRegistry.getAbilityDelegator().getAppContext(), "url", null, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                assertEquals(200, statusCode);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }

            @Override
            public void onFinish() {
                super.onFinish();
                LocalHiLog.info("AsyncHttpResponseHandler", "onFinish");
                assertNull(null);
                signal.countDown();
                resultFlg[0] = true;
            }
        });
        try {
            LocalHiLog.info("testAsyncHttpClient", "signal.await");
            signal.await(20, TimeUnit.SECONDS); // wait for callback
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        assertTrue(resultFlg[0]);
    }
}
